package ivansalvadori.diariopushweb.view.termo;

import ivansalvadori.diariopushweb.model.Termo;
import ivansalvadori.diariopushweb.service.UsuarioService;
import ivansalvadori.diariopushweb.view.HomePage;
import ivansalvadori.diariopushweb.view.security.MySession;
import ivansalvadori.diariopushweb.view.security.SecurePage;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.AbstractItem;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.spring.injection.annot.SpringBean;

@SuppressWarnings("serial")
public class GerenciadorTermo extends WebPage implements SecurePage {

	@SpringBean
	private UsuarioService usuarioService;

	private TermoForm termoForm;

	private RepeatingView repeatingTermo;

	public GerenciadorTermo() {

		add(new FeedbackPanel("feedback"));

		add(new Label("nomeUsuario", ((MySession) getSession()).getUsuario().getNome() ) );
		add(new Label("emailUsuario", ((MySession) getSession()).getUsuario().getEmail() ) );

		Link<GerenciadorTermo> linkLogOut = new Link<GerenciadorTermo>(
				"linkLogOut") {
			@Override
			public void onClick() {
				((MySession) getSession()).logout();
				getSession().clear();
				getSession().invalidateNow();

				((MySession) getSession()).clear();
				((MySession) getSession()).invalidateNow();
				setResponsePage(HomePage.class);
			}
		};

		add(linkLogOut);

		populartabelaTermos();
		add(repeatingTermo);

		termoForm = new TermoForm(new Termo());
		add(termoForm);
	}

	private void populartabelaTermos() {
		repeatingTermo = new RepeatingView("tabelaTermos");

		for (final Termo t : usuarioService
				.listarTermos(((MySession) getSession()).getUsuario())) {
			AbstractItem item = new AbstractItem(repeatingTermo.newChildId());
			repeatingTermo.add(item);
			item.add(new Label("termo", String.valueOf(t.getTermo())));
			item.add(new Label("tipo", String.valueOf(t.getTipo())));
			item.add(new Label("diario", String.valueOf(t.getDiarios().get(0)
					.getEntidade())));

			Link<GerenciadorTermo> link1 = new Link<GerenciadorTermo>(
					"linkRemover") {
				@Override
				public void onClick() {
					usuarioService.removerTermo(t.getCodigo());
					setResponsePage(GerenciadorTermo.class);
				}
			};

			item.add(link1);

		}

	}

}
